package com.gaoyi.basemodule.baseAdapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.viewpager.widget.PagerAdapter;

import java.util.List;

public abstract class BasePagerAdapter<T, B extends ViewDataBinding> extends PagerAdapter {

    protected final Context context;
    protected final List<T> list;

    public BasePagerAdapter(Context context, List<T> list) {
        this.context = context;
        this.list = list;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        B binding = DataBindingUtil.inflate(LayoutInflater.from(context), getLayoutResId(), container, false);
        T t = list.get(position);
        setBindingVariable(binding, position);
        binding.executePendingBindings();
        onBindItem(binding, t, position);
        container.addView(binding.getRoot());
        return binding.getRoot();
    }

    protected abstract void setBindingVariable(B binding, int position);

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View) object);
    }

    @Override
    public int getCount() {
        return list.size();
    }

    public abstract void onBindItem(B binding, T bean, int position);

    protected abstract @LayoutRes
    int getLayoutResId();

    protected OnItemLongClickListener onItemLongClickListener;

    public void setOnItemLongClickListener(OnItemLongClickListener onItemLongClickListener) {
        this.onItemLongClickListener = onItemLongClickListener;
    }

    public interface OnItemLongClickListener {
        void onLongClickListener(View v, int position);
    }

    protected OnItemClickListener onItemClickListener;

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public interface OnItemClickListener {
        void onClickListener(View v, int position);
    }
}
